<template>
  <div class="hot-container">
    <!-- 顶部搜索栏 -->
    <div class="search-header">
      <h1 class="page-title">热门</h1>
      <button class="search-btn" @click="goToSearch">
        <svg viewBox="0 0 24 24" fill="currentColor">
          <path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"/>
        </svg>
      </button>
    </div>

    <div class="video-list" ref="videoList">
      <div 
        v-for="(video, index) in videos" 
        :key="video.media_id"
        class="video-item"
        :class="{ active: currentIndex === index }"
      >
        <!-- 视频播放器 -->
        <video
          ref="videoRefs"
          :src="video.media_url"
          class="video"
          loop
          preload="metadata"
          :muted="currentIndex !== index"
          @click="togglePlay(index)"
          @play="handleVideoPlay(index)"
          @pause="handleVideoPause(index)"
        ></video>

        <!-- 视频信息遮罩层 -->
        <div class="video-info">
          <!-- 用户信息 -->
          <div class="user-info">

            <img 
              :src="video.user.avatar_url" 
              :alt="video.user.nickname" 
              class="avatar"
              @click="goToUserProfile(video.user.user_id)"
            >
            <span class="username" @click="goToUserProfile(video.user.user_id)">{{ video.user.nickname }}</span>
            <button 
              v-if="!isOwnVideo(video.user.user_id)"
              class="follow-btn" 
              :class="{ 'following': isFollowing(video.user.user_id) }"
              @click="handleFollow(video)"
            >
              {{ isFollowing(video.user.user_id) ? '已关注' : '关注' }}
            </button>
          </div>

          <!-- 视频标题和简介 -->
          <div class="video-details">
            <div class="title">{{ video.note.title }}</div>
            <div class="description">{{ video.note.description }}</div>
          </div>
        </div>

        <!-- 互动按钮 -->
        <div class="video-actions">
          <div class="action-btn" @click="handleLike(video)">
            <i class="action-icon" :class="{ 'active': video.isLiked }">
              <svg viewBox="0 0 24 24" fill="currentColor">
                <path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z"/>
              </svg>
            </i>
            <span>{{ video.note.like_count || 0 }}</span>
          </div>
          <div class="action-btn" @click="handleComment(video)">
            <i class="action-icon">
              <svg viewBox="0 0 24 24" fill="currentColor">
                <path d="M21.99 4c0-1.1-.89-2-1.99-2H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h14l4 4-.01-18zM18 14H6v-2h12v2zm0-3H6V9h12v2zm0-3H6V6h12v2z"/>
              </svg>
            </i>
            <span>{{ video.note.comment_count || 0 }}</span>
          </div>
          <div class="action-btn" @click="handleFavorite(video)">
            <i class="action-icon" :class="{ 'active': video.isFavorited }">
              <svg viewBox="0 0 24 24" fill="currentColor">
                <path d="M17 3H7c-1.1 0-2 .9-2 2v16l7-3 7 3V5c0-1.1-.9-2-2-2zm0 15l-5-2.18L7 18V5h10v13z"/>
              </svg>
            </i>
            <span>{{ video.note.favorite_count || 0 }}</span>
          </div>
          <div class="action-btn" @click="handleShare(video)">
            <i class="action-icon">
              <svg viewBox="0 0 24 24" fill="currentColor">
                <path d="M18 16.08c-.76 0-1.44.3-1.96.77L8.91 12.7c.05-.23.09-.46.09-.7s-.04-.47-.09-.7l7.05-4.11c.54.5 1.25.81 2.04.81 1.66 0 3-1.34 3-3s-1.34-3-3-3-3 1.34-3 3c0 .24.04.47.09.7L8.04 9.81C7.5 9.31 6.79 9 6 9c-1.66 0-3 1.34-3 3s1.34 3 3 3c.79 0 1.5-.31 2.04-.81l7.12 4.16c-.05.21-.08.43-.08.65 0 1.61 1.31 2.92 2.92 2.92s2.92-1.31 2.92-2.92-1.31-2.92-2.92-2.92z"/>
              </svg>
            </i>
            <span>分享</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 评论模态框 -->
    <div class="modal-mask" v-if="showCommentModal" @click="closeCommentModal"></div>
    <div class="comment-modal" :class="{ show: showCommentModal }">
      <div class="comment-header">
        <h3>评论 ({{ currentVideo?.note?.comment_count || 0 }})</h3>
        <button @click="closeCommentModal">×</button>
      </div>
      <div class="comment-list">
        <!-- 加载状态 -->
        <div v-if="loadingComments" class="loading-comments">
          <div class="loading-spinner"></div>
          <span>加载评论中...</span>
        </div>
        
        <!-- 空状态 -->
        <div v-else-if="comments.length === 0" class="empty-comments">
          <span>暂无评论，快来抢沙发~</span>
        </div>
        
        <!-- 评论列表 -->
        <div v-else v-for="comment in comments" :key="comment.comment_id" class="comment-item">
          <div class="comment-user">
            <img 
              :src="comment.user?.avatar_url || 'https://picsum.photos/40/40'" 
              :alt="comment.user?.nickname" 
              class="avatar"
              @click="goToUserProfile(comment.user?.user_id)"
            >
            <span class="username" @click="goToUserProfile(comment.user?.user_id)">{{ comment.user?.nickname || '匿名用户' }}</span>
            <span class="comment-time">{{ comment.time }}</span>
          </div>
          <div class="comment-content">{{ comment.content }}</div>
          <div class="comment-actions">
            <div class="like-btn" @click="handleCommentLike(comment)">
              <i class="action-icon" :class="{ 'active': comment.isLiked }">
                <svg viewBox="0 0 24 24" fill="currentColor">
                  <path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z"/>
                </svg>
              </i>
              <span>{{ comment.like_count || 0 }}</span>
            </div>
            <div class="reply-btn" @click="showReplyInput(comment)">
              <i class="action-icon">
                <svg viewBox="0 0 24 24" fill="currentColor">
                  <path d="M21.99 4c0-1.1-.89-2-1.99-2H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h14l4 4-.01-18zM18 14H6v-2h12v2zm0-3H6V9h12v2zm0-3H6V6h12v2z"/>
                </svg>
              </i>
              <span>回复</span>
            </div>
          </div>
          
          <!-- 回复输入框 -->
          <div v-if="comment.showReplyInput" class="reply-input-container">
            <input 
              type="text" 
              v-model="comment.replyContent" 
              placeholder="回复评论..."
              @keyup.enter="submitReply(comment)"
            >
            <button class="send-btn" @click="submitReply(comment)">发送</button>
          </div>
          
          <!-- 评论回复 -->
          <div v-if="comment.replies && comment.replies.length > 0" class="comment-replies">
            <div v-for="reply in comment.replies" :key="reply.reply_id" class="reply-item">
              <div class="reply-user">
                <img 
                  :src="reply.user?.avatar_url || 'https://picsum.photos/40/40'" 
                  :alt="reply.user?.nickname" 
                  class="avatar"
                  @click="goToUserProfile(reply.user?.user_id)"
                >
                <span class="username" @click="goToUserProfile(reply.user?.user_id)">{{ reply.user?.nickname || '匿名用户' }}</span>
                <span class="reply-time">{{ reply.time }}</span>
              </div>
              <div class="reply-content">{{ reply.content }}</div>
              <div class="reply-actions">
                <div class="like-btn" @click="handleReplyLike(reply)">
                  <i class="action-icon" :class="{ 'active': reply.isLiked }">
                    <svg viewBox="0 0 24 24" fill="currentColor">
                      <path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z"/>
                    </svg>
                  </i>
                  <span>{{ reply.like_count || 0 }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="comment-input">
        <input 
          type="text" 
          v-model="commentContent" 
          placeholder="说点什么..."
          @keyup.enter="submitComment"
        >
        <button class="send-btn" @click="submitComment">发送</button>
      </div>
    </div>

    <!-- 底部导航栏 -->
    <nav-footer />
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted, nextTick, onBeforeUnmount } from 'vue';
import axios from 'axios';
import NavFooter from '../../components/NavFooter.vue';
import { useRouter } from 'vue-router';

export default {
  name: 'Hot',
  components: {
    NavFooter
  },
  
  setup() {
    const videos = ref([]);
    const currentIndex = ref(0);
    const videoRefs = ref([]);
    const videoList = ref(null);
    const showCommentModal = ref(false);
    const commentContent = ref('');
    const currentVideo = ref(null);
    const comments = ref([]);
    const loadingComments = ref(false);
    const followingList = ref([]); // 存储关注列表
    const currentUserId = ref(localStorage.getItem('user_id')); // 修改为 user_id
    const router = useRouter();

    // 视频播放状态管理
    const videoStates = ref(new Map());
    const isPlaying = ref(false);
    const playPromise = ref(null);
    const hasUserInteracted = ref(false);
    const isInitialLoad = ref(true);
    const isPlayingPromise = ref(null);

    // 检查登录状态
    const checkLogin = () => {
      const userId = localStorage.getItem('user_id');
      console.log('检查登录状态:', {
        userId,
        isLoggedIn: !!userId
      });
      return !!userId;
    };

    // 获取视频列表
    const fetchVideos = async () => {
      try {
        const response = await axios.get('http://1.14.98.17:8765/api/media/type/video');
        if (response.data.success) {
          const videoPromises = response.data.data.map(async (media) => {
            try {
              // 获取笔记信息
              const noteRes = await axios.get(`http://1.14.98.17:8765/api/notes/${media.note_id}`);
              // 获取用户信息
              const userRes = await axios.get(`http://1.14.98.17:8765/api/users/${noteRes.data.data.user_id}`);
              
              // 获取评论列表
              const commentsRes = await axios.get(`http://1.14.98.17:8765/api/notes/${media.note_id}/comments`);
              let totalCommentCount = 0;
              
              if (commentsRes.data.success) {
                const commentsList = commentsRes.data.data;
                // 获取每个评论的回复数
                const repliesPromises = commentsList.map(async (comment) => {
                  try {
                    const repliesRes = await axios.get(`http://1.14.98.17:8765/api/comments/${comment.comment_id}/replies`);
                    if (repliesRes.data.success) {
                      return repliesRes.data.data.length;
                    }
                    return 0;
                  } catch (error) {
                    console.error('获取回复数失败:', error);
                    return 0;
                  }
                });
                
                const repliesCounts = await Promise.all(repliesPromises);
                totalCommentCount = repliesCounts.reduce((sum, count) => sum + count, 0);
                
                // 更新笔记的评论数（评论数 + 回复数）
                noteRes.data.data.comment_count = commentsList.length + totalCommentCount;
              }

              // 获取点赞用户列表
              const likesRes = await axios.get(`http://1.14.98.17:8765/api/notes/${media.note_id}/likes`);
              if (likesRes.data.success) {
                // 使用点赞用户列表的长度作为点赞数
                noteRes.data.data.like_count = likesRes.data.data.length;
                // 检查当前用户是否在点赞列表中
                const isLiked = likesRes.data.data.some(like => like.user_id === currentUserId.value);
                noteRes.data.data.isLiked = isLiked;
              }

              // 获取收藏用户列表
              const favoritesRes = await axios.get(`http://1.14.98.17:8765/api/notes/${media.note_id}/favorites`);
              if (favoritesRes.data.success) {
                // 使用收藏用户列表的长度作为收藏数
                noteRes.data.data.favorite_count = favoritesRes.data.data.length;
                // 检查当前用户是否在收藏列表中
                const isFavorited = favoritesRes.data.data.some(favorite => favorite.user_id === currentUserId.value);
                noteRes.data.data.isFavorited = isFavorited;
              }
              
              return {
                ...media,
                note: noteRes.data.data,
                user: userRes.data.data,
                isLiked: noteRes.data.data.isLiked || false,
                isFavorited: noteRes.data.data.isFavorited || false
              };
            } catch (error) {
              console.error('获取视频详细信息失败:', error);
              return null;
            }
          });
          
          const results = await Promise.all(videoPromises);
          const validVideos = results.filter(video => video !== null);
          
          // 按发布时间排序（最新的排在前面）
          videos.value = validVideos.sort((a, b) => {
            const timeA = new Date(a.note.updated_at || a.note.create_time);
            const timeB = new Date(b.note.updated_at || b.note.create_time);
            return timeB - timeA; // 降序排列，最新的在前面
          });
          
          console.log('按发布时间排序后的视频列表:', videos.value.map(v => ({
            title: v.note.title,
            time: v.note.updated_at || v.note.create_time
          })));
          
          // 初始化第一个视频
          nextTick(async () => {
            if (videoRefs.value[0] && isInitialLoad.value) {
              const video = videoRefs.value[0];
              video.muted = true;
              try {
                // 创建新的播放Promise
                isPlayingPromise.value = video.play();
                await isPlayingPromise.value;
              } catch (error) {
                console.error('初始视频播放失败:', error);
              } finally {
                isPlayingPromise.value = null;
              }
            }
          });
        }
      } catch (error) {
        console.error('获取视频列表失败:', error);
      }
    };

    // 处理用户交互
    const handleUserInteraction = async (video) => {
      if (!video) return;
      
      try {
        if (playPromise.value) {
          await playPromise.value;
        }
        
        if (video.paused) {
          await playVideo(video);
        } else {
          await pauseVideo(video);
        }
      } catch (error) {
        console.error('视频交互失败:', error);
      }
    };

    // 播放视频的通用方法
    const playVideo = async (video) => {
      if (!video || isPlaying.value) return;
      
      try {
        isPlaying.value = true;
        // 如果有正在进行的播放操作，等待它完成
        if (playPromise.value) {
          await playPromise.value;
        }
        
        // 设置新的播放操作
        playPromise.value = video.play();
        await playPromise.value;
        video.muted = false;
      } catch (error) {
        if (error.name === 'AbortError') {
          console.log('播放被中断');
        } else {
          console.error('视频播放失败:', error);
        }
      } finally {
        isPlaying.value = false;
        playPromise.value = null;
      }
    };

    // 处理视频播放
    const togglePlay = async (index) => {
      const video = videoRefs.value[index];
      if (!video) return;

      if (video.paused) {
        await playVideo(video);
      } else {
        // 如果有正在进行的播放操作，等待它完成
        if (isPlayingPromise.value) {
          try {
            await isPlayingPromise.value;
          } catch (error) {
            console.error('等待之前的播放操作完成失败:', error);
          }
        }
        video.pause();
        videoStates.value.set(index, false);
        isPlaying.value = false;
      }
    };

    // 处理滚动
    const handleScroll = async () => {
      if (loadingComments.value) return;
      
      const videos = document.querySelectorAll('video');
      const viewportHeight = window.innerHeight;
      const scrollTop = window.scrollY;
      
      for (const video of videos) {
        const rect = video.getBoundingClientRect();
        const videoTop = rect.top + scrollTop;
        const videoBottom = videoTop + rect.height;
        
        // 如果视频在视口内
        if (rect.top < viewportHeight && rect.bottom > 0) {
          // 如果视频中心点在视口内，播放视频
          const videoCenter = videoTop + rect.height / 2;
          if (videoCenter > scrollTop && videoCenter < scrollTop + viewportHeight) {
            if (video.paused) {
              await playVideo(video);
            }
          } else {
            if (!video.paused) {
              await pauseVideo(video);
            }
          }
        } else {
          // 如果视频不在视口内，暂停视频
          if (!video.paused) {
            await pauseVideo(video);
          }
        }
      }
    };

    // 点赞处理
    const handleLike = async (video) => {
      if (!checkLogin()) return;

      try {
        const response = await axios.post(`http://1.14.98.17:8765/api/notes/${video.note_id}/like`, {
          userId: currentUserId.value
        });
        
        if (response.data.success) {
          video.isLiked = !video.isLiked;
          video.note.like_count += video.isLiked ? 1 : -1;
        }
      } catch (error) {
        console.error('点赞失败:', error);
      }
    };

    // 收藏处理
    const handleFavorite = async (video) => {
      if (!checkLogin()) return;

      try {
        const response = await axios.post(`http://1.14.98.17:8765/api/notes/${video.note_id}/favorite`, {
          userId: currentUserId.value
        });
        
        if (response.data.success) {
          video.isFavorited = !video.isFavorited;
          video.note.favorite_count += video.isFavorited ? 1 : -1;
        }
      } catch (error) {
        console.error('收藏失败:', error);
      }
    };

    // 获取评论列表
    const fetchComments = async (noteId) => {
      console.log(noteId);
      
      if (!noteId) return;
      
      loadingComments.value = true;
      try {
        const response = await axios.get(`http://1.14.98.17:8765/api/notes/${noteId}/comments`);
        if (response.data.success) {
          // 获取评论列表
          const commentsList = response.data.data;
          let totalCommentCount = 0;
          
          // 获取每个评论的用户信息和回复
          const commentsWithUserInfo = await Promise.all(
            commentsList.map(async (comment) => {
              try {
                // 获取用户信息
                const userResponse = await axios.get(`http://1.14.98.17:8765/api/users/${comment.user_id}`);
                // 获取评论回复
                const repliesResponse = await axios.get(`http://1.14.98.17:8765/api/comments/${comment.comment_id}/replies`);
                
                // 累加回复数
                if (repliesResponse.data.success) {
                  totalCommentCount += repliesResponse.data.data.length;
                }
                
                // 获取回复的用户信息
                const repliesWithUserInfo = repliesResponse.data.success ? 
                  await Promise.all(repliesResponse.data.data.map(async (reply) => {
                    try {
                      const replyUserResponse = await axios.get(`http://1.14.98.17:8765/api/users/${reply.user_id}`);
                      return {
                        ...reply,
                        user: replyUserResponse.data.success ? replyUserResponse.data.data : null
                      };
                    } catch (error) {
                      console.error('获取回复用户信息失败:', error);
                      return reply;
                    }
                  })) : [];

                return {
                  ...comment,
                  user: userResponse.data.success ? userResponse.data.data : null,
                  replies: repliesWithUserInfo
                };
              } catch (error) {
                console.error('获取评论信息失败:', error);
                return comment;
              }
            })
          );
          
          // 更新总评论数（评论数 + 回复数）
          if (currentVideo.value) {
            currentVideo.value.note.comment_count = commentsList.length + totalCommentCount;
          }
          
          comments.value = commentsWithUserInfo;
        }
      } catch (error) {
        console.error('获取评论失败:', error);
      } finally {
        loadingComments.value = false;
      }
    };

    // 评论处理
    const handleComment = async (video) => {
      if (!checkLogin()) return;
      currentVideo.value = video;
      showCommentModal.value = true;
      await fetchComments(video.note_id);
    };

    // 生成UUID的兼容方法
    const generateUUID = () => {
      if (typeof crypto !== 'undefined' && crypto.randomUUID) {
        return crypto.randomUUID();
      }
      // 兼容性UUID生成
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        const r = Math.random() * 16 | 0;
        const v = c === 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
      });
    };

    // 提交评论
    const submitComment = async () => {
      if (!checkLogin()) {
        return;
      }

      if (!commentContent.value.trim()) {
        return;
      }

      try {
        const response = await axios.post('http://1.14.98.17:8765/api/comments', {
          comment_id: generateUUID(),
          note_id: currentVideo.value.note_id,
          user_id: currentUserId.value,
          content: commentContent.value,
          time: new Date().toISOString().split('T')[0]
        });

        if (response.data.success) {
          currentVideo.value.note.comment_count++;
          commentContent.value = '';
          // 重新获取评论列表
          await fetchComments(currentVideo.value.note_id);
        }
      } catch (error) {
        console.error('评论失败:', error);
      }
    };

    // 分享处理
    const handleShare = (video) => {
      if (!checkLogin()) return;
      // 分享功能待实现
      alert('分享功能开发中...');
    };

    // 关闭评论弹窗
    const closeCommentModal = () => {
      showCommentModal.value = false;
    };

    // 组件卸载时清理
    onBeforeUnmount(() => {
      if (playPromise) {
        clearTimeout(playPromise);
      }
      videoStates.value.clear();
      // 移除事件监听
      document.removeEventListener('click', handleUserInteraction);
      document.removeEventListener('touchstart', handleUserInteraction);
      if (videoList.value) {
        videoList.value.removeEventListener('scroll', handleScroll);
      }
    });

    // 监听视频播放状态
    const handleVideoPlay = (index) => {
      videoStates.value.set(index, true);
      isPlaying.value = true;
    };

    const handleVideoPause = (index) => {
      videoStates.value.set(index, false);
      isPlaying.value = false;
    };

    // 评论点赞处理
    const handleCommentLike = async (comment) => {
      if (!checkLogin()) return;

      try {
        const response = await axios.post(`http://1.14.98.17:8765/api/comments/${comment.comment_id}/like`, {
          user_id: currentUserId.value
        });
        
        if (response.data.success) {
          comment.isLiked = !comment.isLiked;
          comment.like_count = (comment.like_count || 0) + (comment.isLiked ? 1 : -1);
        }
      } catch (error) {
        console.error('评论点赞失败:', error);
      }
    };

    // 回复点赞处理
    const handleReplyLike = async (reply) => {
      if (!checkLogin()) return;

      try {
        const response = await axios.post(`http://1.14.98.17:8765/api/comments/${reply.comment_id}/like`, {
          user_id: currentUserId.value
        });
        
        if (response.data.success) {
          reply.isLiked = !reply.isLiked;
          reply.like_count = (reply.like_count || 0) + (reply.isLiked ? 1 : -1);
        }
      } catch (error) {
        console.error('回复点赞失败:', error);
      }
    };

    // 修改 pauseVideo 函数
    const pauseVideo = async (video) => {
      if (!video) return;
      
      try {
        if (playPromise.value) {
          await playPromise.value;
        }
        await video.pause();
      } catch (error) {
        console.error('视频暂停失败:', error);
      }
    };

    // 显示回复输入框
    const showReplyInput = (comment) => {
      if (!checkLogin()) return;
      comment.showReplyInput = true;
      comment.replyContent = '';
    };

    // 提交回复
    const submitReply = async (comment) => {
      if (!checkLogin()) return;

      if (!comment.replyContent?.trim()) return;

      try {
        const response = await axios.post(`http://1.14.98.17:8765/api/comments/${comment.comment_id}/replies`, {
          reply_id: generateUUID(),
          user_id: currentUserId.value,
          content: comment.replyContent,
          time: new Date().toISOString().split('T')[0]
        });

        if (response.data.success) {
          // 重新获取评论列表以更新回复
          await fetchComments(currentVideo.value.note_id);
          comment.showReplyInput = false;
          comment.replyContent = '';
        }
      } catch (error) {
        console.error('回复失败:', error);
      }
    };

    // 跳转到用户主页
    const goToUserProfile = (userId) => {
      if (!userId) return;
      window.location.href = `/#/usercont?userId=${userId}`;
    };

    // 跳转到搜索页面
    const goToSearch = () => {
      router.push('/search');
    };

    // 获取关注列表
    const fetchFollowingList = async () => {
      if (!checkLogin()) {
        console.log('未登录，跳过获取关注列表');
        return;
      }
      console.log('开始获取关注列表，当前用户ID:', currentUserId.value);
      try {
        const response = await axios.get(`http://1.14.98.17:8765/api/profile/${currentUserId.value}/following`);
        console.log('获取关注列表响应:', response.data);
        if (response.data.success) {
          const oldList = [...followingList.value];
          followingList.value = response.data.data.following;
          console.log('关注列表更新对比:');
          console.log('更新前:', oldList);
          console.log('更新后:', followingList.value);
          console.log('变化:', {
            added: followingList.value.filter(id => !oldList.includes(id)),
            removed: oldList.filter(id => !followingList.value.includes(id))
          });
        } else {
          console.warn('获取关注列表失败:', response.data);
        }
      } catch (error) {
        console.error('获取关注列表出错:', error);
        console.error('错误详情:', {
          message: error.message,
          response: error.response?.data,
          status: error.response?.status
        });
      }
    };

    // 处理关注/取消关注
    const handleFollow = async (video) => {
      console.log('点击关注按钮，视频信息:', video);
      
      if (!checkLogin()) {
        console.log('用户未登录，提示登录');
        alert('请先登录后再关注');
        return;
      }

      if (currentUserId.value === video.user.user_id) {
        console.log('尝试关注自己，用户ID:', currentUserId.value);
        alert('不能关注自己');
        return;
      }

      const targetUserId = video.user.user_id;
      console.log('准备关注用户，当前用户ID:', currentUserId.value, '目标用户ID:', targetUserId);

      try {
        console.log('发送关注请求...');
        const response = await axios.post(
          `http://1.14.98.17:8765/api/profile/${currentUserId.value}/follow/${targetUserId}`
        );
        console.log('关注请求响应:', response.data);
        
        if (response.data.success) {
          // 更新关注状态
          const oldList = [...followingList.value];
          const isCurrentlyFollowing = oldList.includes(targetUserId);
          console.log('当前关注状态:', isCurrentlyFollowing ? '已关注' : '未关注');
          
          if (isCurrentlyFollowing) {
            followingList.value = oldList.filter(id => id !== targetUserId);
            console.log('取消关注操作:');
            console.log('操作前列表:', oldList);
            console.log('操作后列表:', followingList.value);
            console.log('移除的用户ID:', targetUserId);
          } else {
            followingList.value = [...oldList, targetUserId];
            console.log('添加关注操作:');
            console.log('操作前列表:', oldList);
            console.log('操作后列表:', followingList.value);
            console.log('新增的用户ID:', targetUserId);
          }
        } else {
          console.warn('关注操作失败:', response.data);
          alert('操作失败，请重试');
        }
      } catch (error) {
        console.error('关注操作出错:', error);
        console.error('错误详情:', {
          message: error.message,
          response: error.response?.data,
          status: error.response?.status
        });
        alert('操作失败，请重试');
      }
    };

    // 检查是否已关注
    const isFollowing = (userId) => {
      const result = followingList.value.includes(userId);
      console.log('检查关注状态:');
      console.log('当前关注列表:', followingList.value);
      console.log('检查用户ID:', userId);
      console.log('是否已关注:', result);
      return result;
    };

    // 检查是否是自己的作品
    const isOwnVideo = (userId) => {
      const result = currentUserId.value === userId;
      console.log('检查是否自己的作品:');
      console.log('当前用户ID:', currentUserId.value);
      console.log('视频作者ID:', userId);
      console.log('是否自己的作品:', result);
      return result;
    };

    onMounted(async () => {
      console.log('组件挂载，开始初始化...');
      console.log('当前用户ID:', currentUserId.value);
      console.log('登录状态:', checkLogin() ? '已登录' : '未登录');
      console.log('初始关注列表:', followingList.value);
      await fetchFollowingList();
      console.log('关注列表获取完成，当前关注列表:', followingList.value);
      console.log('开始获取视频列表...');
      fetchVideos();
      // 添加用户交互监听
      document.addEventListener('click', handleUserInteraction);
      document.addEventListener('touchstart', handleUserInteraction);
      // 添加滚动监听
      if (videoList.value) {
        videoList.value.addEventListener('scroll', handleScroll);
      }
    });

    onUnmounted(() => {
      if (videoList.value) {
        videoList.value.removeEventListener('scroll', handleScroll);
      }
    });

    return {
      videos,
      currentIndex,
      videoRefs,
      videoList,
      showCommentModal,
      commentContent,
      currentVideo,
      comments,
      loadingComments,
      followingList,
      currentUserId,
      togglePlay,
      handleScroll,
      handleLike,
      handleFavorite,
      handleComment,
      handleShare,
      submitComment,
      closeCommentModal,
      handleVideoPlay,
      handleVideoPause,
      hasUserInteracted,
      isInitialLoad,
      handleCommentLike,
      handleReplyLike,
      showReplyInput,
      submitReply,
      goToUserProfile,
      handleFollow,
      isFollowing,
      isOwnVideo,
      checkLogin,
      goToSearch
    };
  }
};
</script>

<style scoped>
.hot-container {
  width: 100%;
  height: 100vh;
  background-color: #000;
  position: relative;
}

/* 搜索头部 */
.search-header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  background: linear-gradient(to bottom, rgba(0,0,0,0.8), transparent);
  color: #fff;
}

.page-title {
  font-size: 32px;
  font-weight: bold;
  margin: 0;
}

.search-btn {
  background: none;
  border: none;
  color: #fff;
  width: 44px;
  height: 44px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: background-color 0.2s ease;
  cursor: pointer;
}

.search-btn:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

.search-btn svg {
  width: 24px;
  height: 24px;
}

.video-list {
  width: 100%;
  height: 100%;
  overflow-y: scroll;
  scroll-snap-type: y mandatory;
  -webkit-overflow-scrolling: touch;
}

.video-item {
  width: 100%;
  height: 100vh;
  scroll-snap-align: start;
  position: relative;
  background-color: #000;
  display: flex;
  justify-content: center;
  align-items: center;
}

.video {
  width: 100%;
  height: 100%;
  object-fit: contain;
  background-color: #000;
}

.video-info {
  position: absolute;
  bottom: 100px;
  left: 0;
  width: 100%;
  padding: 25px;
  color: #fff;
  background: linear-gradient(transparent, rgba(0, 0, 0, 0.7));
  z-index: 1;
}

.user-info {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.avatar {
  width: 65px;
  height: 65px;
  border-radius: 50%;
  margin-right: 20px;
  border: 3px solid #fff;
  cursor: pointer;
  transition: transform 0.2s;
}

.avatar:hover {
  transform: scale(1.1);
}

.username {
  font-size: 22px;
  font-weight: bold;
  margin-right: 20px;
  cursor: pointer;
  transition: color 0.2s;
}

.username:hover {
  color: #ff2442;
}

.follow-btn {
  padding: 4px 12px;
  border-radius: 20px;
  border: 1px solid #ff2442;
  background: transparent;
  color: #ff2442;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
}

.follow-btn:hover {
  background: #ff2442;
  color: white;
}

.follow-btn.following {
  background: #ff2442;
  color: white;
}

.follow-btn.following:hover {
  background: transparent;
  color: #ff2442;
}

.video-details {
  margin-top: 20px;
}

.video-details .title {
  font-size: 24px;
  margin-bottom: 12px;
  font-weight: bold;
}

.video-details .description {
  font-size: 20px;
  opacity: 0.9;
  line-height: 1.5;
}

.video-actions {
  position: absolute;
  right: 30px;
  bottom: 160px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 35px;
  z-index: 1;
}

.action-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #fff;
  font-size: 18px;
  cursor: pointer;
  padding: 8px;
}

.action-icon {
  font-size: 48px;
  margin-bottom: 8px;
  line-height: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.action-icon svg {
  width: 48px;
  height: 48px;
}

.action-icon.active {
  color: #ff2442;
  transform: scale(1.1);
}

.action-icon.active svg {
  fill: #ff2442;
}

.comment-modal {
  position: fixed;
  bottom: 60px;
  left: 0;
  width: 100%;
  height: calc(60vh - 60px);
  background: #fff;
  z-index: 1001;
  display: flex;
  flex-direction: column;
  border-radius: 20px 20px 0 0;
  transform: translateY(100%);
  transition: transform 0.3s ease-out;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
}

.comment-modal.show {
  transform: translateY(0);
}

.comment-header {
  padding: 20px;
  background: #fff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #eee;
  border-radius: 20px 20px 0 0;
}

.comment-header h3 {
  margin: 0;
  font-size: 24px;
  font-weight: bold;
}

.comment-header button {
  background: none;
  border: none;
  font-size: 36px;
  cursor: pointer;
  padding: 8px;
  color: #666;
}

.comment-list {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  padding-bottom: 100px;
  background: #fff;
}

.comment-item {
  margin-bottom: 25px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f5f5f5;
}

.comment-user {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.comment-user .avatar {
  width: 70px;
  height: 70px;
  border-radius: 50%;
  margin-right: 15px;
}

.comment-user .username {
  font-size: 25px;
  font-weight: 500;
  color: #333;
}

.comment-content {
  margin-left: 100px;
  font-size: 20px;
  line-height: 1.5;
  color: #333;
}

.comment-actions {
  display: flex;
  align-items: center;
  margin-top: 8px;
  margin-left: 100px;
}

.like-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  cursor: pointer;
  padding: 6px 10px;
  border-radius: 12px;
  transition: background-color 0.3s;
}

.like-btn:hover {
  background-color: #f5f5f5;
}

.like-btn .action-icon {
  width: 22px;
  height: 22px;
  color: #999;
}

.like-btn .action-icon.active {
  color: #ff2442;
}

.like-btn span {
  font-size: 18px;
  color: #999;
}

.comment-time {
  font-size: 18px;
  color: #999;
  margin-left: 12px;
}

.comment-replies {
  margin-left: 100px;
  margin-top: 12px;
  padding-left: 12px;
  border-left: 2px solid #f0f0f0;
}

.reply-item {
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f5f5f5;
}

.reply-item:last-child {
  margin-bottom: 0;
  padding-bottom: 0;
  border-bottom: none;
}

.reply-user {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.reply-user .avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  margin-right: 10px;
}

.reply-user .username {
  font-size: 20px;
  font-weight: 500;
  color: #333;
}

.reply-time {
  font-size: 16px;
  color: #999;
  margin-left: 8px;
}

.reply-content {
  font-size: 18px;
  line-height: 1.5;
  color: #333;
  margin-left: 60px;
}

.reply-actions {
  margin-left: 60px;
  margin-top: 4px;
}

.reply-actions .like-btn {
  padding: 4px 8px;
}

.reply-actions .like-btn .action-icon {
  width: 18px;
  height: 18px;
}

.reply-actions .like-btn span {
  font-size: 16px;
}

.comment-input {
  position: fixed;
  bottom: 80px;
  left: 0;
  right: 0;
  padding: 20px;
  background: #fff;
  border-top: 1px solid #eee;
  display: flex;
  align-items: center;
  gap: 20px;
  z-index: 1002;
}

.comment-input input {
  flex: 1;
  padding: 15px 25px;
  border: 2px solid #ddd;
  border-radius: 30px;
  outline: none;
  font-size: 17px;
  background: #f5f5f5;
}

.send-btn {
  padding: 15px 35px;
  background: #ff2442;
  color: #fff;
  border: none;
  border-radius: 30px;
  cursor: pointer;
  font-size: 17px;
  font-weight: bold;
  transition: background-color 0.2s ease;
}

.send-btn:hover {
  background: #e61e3c;
}

.send-btn:active {
  transform: scale(0.98);
}

/* 添加遮罩层 */
.modal-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  z-index: 1000;
  opacity: 0;
  transition: opacity 0.3s ease-out;
}

.modal-mask.show {
  opacity: 1;
}

.nav-footer {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  background: #fff;
  display: flex;
  justify-content: space-around;
  padding: 15px 0;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  z-index: 1001;
}

.loading-comments {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #999;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #ff2442;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.empty-comments {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #999;
  font-size: 16px;
}

.reply-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  cursor: pointer;
  padding: 6px 10px;
  border-radius: 12px;
  transition: background-color 0.3s;
  margin-left: 12px;
}

.reply-btn:hover {
  background-color: #f5f5f5;
}

.reply-btn .action-icon {
  width: 22px;
  height: 22px;
  color: #999;
}

.reply-btn span {
  font-size: 18px;
  color: #999;
}

.reply-input-container {
  margin-left: 100px;
  margin-top: 12px;
  display: flex;
  gap: 12px;
  align-items: center;
}

.reply-input-container input {
  flex: 1;
  padding: 12px 20px;
  border: 2px solid #ddd;
  border-radius: 20px;
  outline: none;
  font-size: 16px;
  background: #f5f5f5;
}

.reply-input-container .send-btn {
  padding: 12px 24px;
  background: #ff2442;
  color: #fff;
  border: none;
  border-radius: 20px;
  cursor: pointer;
  font-size: 16px;
  font-weight: bold;
}
</style>
